# -*- coding: utf-8 -*-
#*******************************************************************************
#   
#   http://www.mangareader.net/comic-name 解析器
#
#*******************************************************************************
from base import *

# 解析器标签
tag='mangareader'

#---------------------------- 验证模块 ----------------------------

# 每个解析模块都含有这个函数，用来判断链接是否符合该模块
def url_judgement(url):
    if re.match(r'http://www.mangareader.net/[\w-]+',url):
        return valid_check(url)
    return False

# 根据内容检测是否可解析
def valid_check(url):
    print('{} catch {}'.format(tag,url))
    content=request_for(url,common_headers);
    if content:
        return get_loader(url)
    return False

# 下载器获取
def get_loader(url):
    return MangareaderLoader(url,MangareaderPageParser,MangareaderVolParser)

#---------------------------- 下载器 ----------------------------

class MangareaderLoader(ComicLoader):
    def __init__(self,url,comic_page_parser,comic_vol_parser):
        super().__init__(url,comic_page_parser,comic_vol_parser)

#---------------------------- 解析器 ----------------------------

class MangareaderPageParser(ComicPageParser):
    def __init__(self,comic):
        super().__init__(comic)
    
    def work(self,content):
        site_prefix='http://www.mangareader.net'
        # title
        self.comic.title=re.compile(r'<h1>(.*?)</h1>',re.S|re.M).findall(content)[0].strip()
        # description
        self.comic.description=re.compile(r'<p>(.*?)</p>',re.S|re.M).findall(content)[0].strip()
        # cover
        self.comic.cover=re.compile(r'<div id="mangaimg"><img src="(.*?)"',re.S|re.M).findall(content)[0]
         # vols
        vols_content=re.compile(r'<table id="listing">(.*?)</table>',re.S|re.M).findall(content)[0]
        vols_content=re.compile(r'<a href=(.*?)/a> ',re.S|re.M).findall(vols_content)
        for vol in vols_content:
            url=re.compile(r'\"(.*?)\"').findall(vol)[0]
            title=re.compile(r'>(.*?)<').findall(vol)[0]
            self.comic.vols.append(InfoVol(site_prefix+url,title))
        
class MangareaderVolParser(ComicVolParser):
    def __init__(self):
        super().__init__()
        self.site_prefix='http://www.mangareader.net'
        self.pic_index=0
    
    def work(self,content):
        options=re.compile(r'<select id="pageMenu" name="pageMenu">(.*?)</select>',re.S|re.M).findall(content)[0]
        self.feed(options)

    def handle_starttag(self,tag,attrs):
        if tag=='option':
            infos={}
            for attr in attrs:
                infos[attr[0]]=attr[1]
            content=request_for(self.site_prefix+infos['value'],common_headers).decode('utf-8','ignore')
            pic_url_content=re.compile(r'<div id="imgholder">(.*?)</a>',re.S|re.M).findall(content)[0]
            url=re.compile(r'src="(.*?)"',re.S|re.M).findall(pic_url_content)[0]
            self.pic_urls.append((url,zero_prefix(self.pic_index)))
            self.pic_index+=1 